from django.shortcuts import render
from django.template.defaultfilters import title
from rest_framework.views import APIView
from rest_framework.response import Response
from books.models import BooksInfo
from books.serializer import BooksSerializer

# Create your views here.

# def booksView(request):
#     title = '书籍列表'
#
#     s = request.GET.get('s', '')
#     t = request.GET.get('t', '')
#     # readCount = BooksInfo.objects.order_by('readCount')
#     # likes = BooksInfo.objects.order_by('likes')
#     # rating = BooksInfo.objects.order_by('rating')
#
#     if s:
#         booklist = BooksInfo.objects.order_by('-' + s)
#     if t:
#         booklist = BooksInfo.objects.filter(ty)
#     print(s)
#     return render(request, 'books.html', locals())
class booksView(APIView):
    def get(self, request):
        context = {'state': 'success', 'msg': "获取成功", 'data': {}}
        context['data']['BooksInfo'] = []
        sort = request.GET.get('sort', 'likes')
        c = BooksInfo.objects.order_by('-' + sort)
        context['data']['BooksInfo'].append(BooksSerializer(instance=c[::], many=True).data)

        return Response(context)


# def detailView(request, id):
#     # booklist = BooksInfo.objects.get()
#     book = BooksInfo.objects.get(id=id)
#     title = BooksInfo.objects.get(id=id).name
#     img = BooksInfo.objects.get(id=id).img
#     return render(request, 'details.html', locals())

class detailView(APIView):
    def get(self, request, id):
        context = {'state': 'success', 'msg': "获取成功", 'data': {}}
        b = BooksInfo.objects.get(id=id)
        context['data']['book'] = BooksSerializer(instance=b).data
        context['data']['title'] = b.name
        # context['data']['img'] = {b.img}
        # context['data']['con'] = b.details
        context['data']['rating'] = b.rating
        return Response(context)